// SPDX-License-Identifier: GPL-2.0+
/*
 * Copyright (C) 2022 tanghaifeng-gz@loongson.cn
 *
 */

#include <common.h>
#include <dm.h>
#include <wdt.h>
#include <linux/io.h>

DECLARE_GLOBAL_DATA_PTR;

#if defined(CONFIG_MACH_LOONGSON1)
#define WDT_EN			0x0
#define WDT_TIMER		0x4
#define WDT_SET			0x8
#elif defined(CONFIG_MACH_LOONGSON2_SOC) || defined(CONFIG_SB_LS7A1000)
#define RST_CNT		0x00
#define WDT_SET		0x04
#define WDT_TIMER		0x08
#endif

struct ls1x_wdt {
	void __iomem *regs;
};

#define TIMER_REG_TMRSTAT		0x00
#define TIMER_REG_TMR1CTL		0x20
#define TIMER_REG_TMR1LOAD		0x24

#define TMR1CTL_ENABLE			BIT(7)
#define TMR1CTL_RESTART			BIT(9)
#define TMR1CTL_PRESCALE_SHIFT		16

static int ls1x_wdt_ping(struct ls1x_wdt *priv)
{
	writel(0x1, priv->regs + WDT_SET);

	return 0;
}

static int ls1x_wdt_start(struct udevice *dev, u64 ms, ulong flags)
{
	struct ls1x_wdt *priv = dev_get_priv(dev);
	u64 counts;

	counts = gd->bus_clk / 1000 * ms;
	writel(counts, priv->regs + WDT_TIMER);

#if defined(CONFIG_MACH_LOONGSON1)
	writel(0x1, priv->regs + WDT_EN);
#elif defined(CONFIG_MACH_LOONGSON2_SOC) || defined(CONFIG_SB_LS7A1000)
	writel(readl(priv->regs + RST_CNT) | 0x2, priv->regs + RST_CNT);
#endif

	return 0;
}

static int ls1x_wdt_stop(struct udevice *dev)
{
	struct ls1x_wdt *priv = dev_get_priv(dev);

	ls1x_wdt_ping(priv);

#if defined(CONFIG_MACH_LOONGSON1)
	writel(0x0, priv->regs + WDT_EN);
#elif defined(CONFIG_MACH_LOONGSON2_SOC) || defined(CONFIG_SB_LS7A1000)
	writel(readl(priv->regs + RST_CNT) & (~0x2), priv->regs + RST_CNT);
#endif

	return 0;
}

static int ls1x_wdt_reset(struct udevice *dev)
{
	struct ls1x_wdt *priv = dev_get_priv(dev);

	ls1x_wdt_ping(priv);

	return 0;
}

static int ls1x_wdt_probe(struct udevice *dev)
{
	struct ls1x_wdt *priv = dev_get_priv(dev);

	priv->regs = dev_remap_addr(dev);
	if (!priv->regs)
		return -EINVAL;

	ls1x_wdt_stop(dev);

	return 0;
}

static const struct wdt_ops ls1x_wdt_ops = {
	.start = ls1x_wdt_start,
	.reset = ls1x_wdt_reset,
	.stop = ls1x_wdt_stop,
};

static const struct udevice_id ls1x_wdt_ids[] = {
	{ .compatible = "loongson,ls1x-wdt" },
	{ .compatible = "loongson,ls2k-wdt" },
	{ .compatible = "loongson,ls7a-wdt" },
	{}
};

U_BOOT_DRIVER(ls1x_wdt) = {
	.name = "ls1x_wdt",
	.id = UCLASS_WDT,
	.of_match = ls1x_wdt_ids,
	.probe = ls1x_wdt_probe,
	.priv_auto_alloc_size = sizeof(struct ls1x_wdt),
	.ops = &ls1x_wdt_ops,
	.flags = DM_FLAG_PRE_RELOC,
};
